package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.entity.SysDepartment;
import com.tticar.invmanager.entity.SysUser;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.SysDepartmentMapper;
import com.tticar.invmanager.service.ISysDepartmentService;
import com.tticar.invmanager.service.ISysUserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.entity.Columns;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-06-27
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public Page selectPage(SysDepartment sysDepartment, MyPage<SysDepartment> page) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.ne("status", -1);
        Columns columns = Columns.create().column("*")
                .column("(select case count(1) when 0 then 'open' else 'closed' end from sys_department t where t.pid=sys_department.id)", "state");
        wrapper.setSqlSelect(columns);
        wrapper.eq(SysDepartment.PID, sysDepartment.getId());
        wrapper.like(Strings.isNotEmpty(sysDepartment.getName()), SysDepartment.NAME, sysDepartment.getName());
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.ne("status", -1);
            wrapper.eq("dept_id", id);
            List<SysUser> sysUsers = sysUserService.selectList(wrapper);
            if (sysUsers != null && sysUsers.size() > 0) {
                throw new MyServiceException("部门下有人员，禁止删除");
            }
            SysDepartment sysDepartment = new SysDepartment();
            sysDepartment.setId(id);
            //删除为-1，区分删除和禁用
            sysDepartment.setStatus(-1);
            list.add(sysDepartment);
        }
        this.updateBatchById(list);
    }

    @Override
    public List select() {
        Wrapper wrapper = Condition.wrapper();
        wrapper.eq("status", 0);
        wrapper.setSqlSelect(Columns.create().column("id").column("name"));
        return this.selectMaps(wrapper);
    }

}
